#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sstream>

using namespace std;

int main()
{
    int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(listen_sock < 0)
    {
        perror("socket");
        return 0;

    }

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(28989);
    //0.0.0.0 : 本地所有的网卡地址
    addr.sin_addr.s_addr = inet_addr("0.0.0.0");

    int ret = bind(listen_sock, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0)
    {
        perror("bind");
        return 0;
    }

    ret = listen(listen_sock, 1);
    if(ret < 0)
    {
        perror("listen");
        return 0;
    }
    struct sockaddr_in cli_addr;
    socklen_t cli_addrlen = sizeof(cli_addr);
    int newsockfd = accept(listen_sock, (struct sockaddr*)&cli_addr, &cli_addrlen);
    if(newsockfd < 0)
    {
        perror("accept");
        return 0;
    }
    printf("accept new connect from client %s:%d\n", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

    while(1)
    {
        //接收
        char buf[1024] = {0};
        ssize_t recv_size = recv(newsockfd, buf, sizeof(buf) - 1, 0);
        if(recv_size < 0)
        {
            perror("recv");
            continue;
        }
        else if(recv_size == 0)
        {
            printf("peer close connect\n");
            close(newsockfd);
            return 0;
        }

        printf("%s\n", buf);
        memset(buf, '\0', sizeof(buf));

        string body = "<html><h1>bite welcome</h1></html>";
        stringstream ss;
        ss << "HTTP/1.1 302 Found\r\n";
        //ss << "Content-Type: text/html\r\n";
        //ss << "Content-Length: " << body.size() << "\r\n";
        ss << "Location: https://www.baidu.com/\r\n";
        ss << "\r\n";
        send(newsockfd, ss.str().c_str(), ss.str().size(), 0);
        send(newsockfd, body.c_str(), body.size(), 0);
    }

    close(listen_sock);
    return 0;
}
